package com.dy.course.common;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * Created by Joels.Zhou on 2016/12/26
 * 根据消息code,设置控制器返回值responseMessage中的message(国际化)
 * 切点为 @annotation(org.springframework.web.bind.annotation.ResponseBody)
 * 切面类型为Around
 */
@Component
@Aspect
public class MessageAspect {
	/**
	 * 日志
	 */
	private static Logger logger = Logger.getLogger(MessageAspect.class);


//	@Autowired
//	private CacheManager cacheManager;

	/**
	 * @param joinPoint
	 *            切点信息
	 * @return 返回值
	 * @throws Throwable
	 *             切点异常
	 */
	@Around(value = "@annotation(org.springframework.web.bind.annotation.ResponseBody)")
	public Object setMessage(ProceedingJoinPoint joinPoint) throws Throwable {
		ResponseMessage<?> responseMessage = new ResponseMessage<Object>();
		// 返回值
		try {
//			String userJwt = request.getHeader(JwtUtil.JWT_HEADER_KEY);
//			if (!JwtUtil.isJwtValid(userJwt, (String) cacheManager.get(userJwt))) {
//				throw new BaseException(Constant.Code.AUTHENTICATION_ERROR, "鉴权失败", null);
//			}
			responseMessage = (ResponseMessage<?>) joinPoint.proceed();
			// 根据code,利用国际化资源对象获取对应的message,并设置
		} catch (BaseException e) {
			logger.error(e.getMessage(), e);
			responseMessage.setCode(e.getCode());
			// 根据code,利用国际化资源对象获取对应的message,并设置
			responseMessage.setMessage(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			responseMessage.setCode(Constant.Code.SERVER_ERROR);
			responseMessage.setMessage("系统错误");
		}
		return responseMessage;
	}

}
